package com.wnhz.work.yz.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.ProjectOrderAdapter;
import com.wnhz.work.yz.bean.AddressBean;
import com.wnhz.work.yz.bean.ProjectBean;
import com.wnhz.work.yz.bean.ProjectChild1;
import com.wnhz.work.yz.bean.ProjectOrderBean;
import com.wnhz.work.yz.bean.YusuanOrderBean;
import com.wnhz.work.yz.molder.SpecialShopMolder;
import com.wnhz.work.yz.utils.Prefer;
import com.wnhz.work.yz.utils.SystemUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.NoScrollListView;
import com.wnhz.work.yz.view.OrderTime;
import com.wnhz.work.yz.view.SwitchView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * ---项目下单
 */
public class ProjectOrderActivity extends BaseActivity implements View.OnClickListener, SwitchView.OnStateChangedListener {
    private TextView title;
    //    asds
    private NoScrollListView my_listView;
    private ProjectOrderAdapter mAdapter;
    private SwitchView sw_service, sw_need, sw_special, sw_install;
    private RelativeLayout rl_service, rl_message, rl_special, rl_special_money;
    //    private NoScrollListView listView;
    //    private SubmitAdapter submitAdapter;
    private boolean isTrue;
    //所有项目列表
    private ProjectBean bean;
    //选中的下单列表
    private List<ProjectChild1> dataList = new ArrayList<>();
    private List<ProjectChild1> beanList = new ArrayList<>();

    private RelativeLayout rl_has_address;
    private RelativeLayout rl_add_address;

    private static final int CODE_ADDRESS = 111;
    private static final int CODE_PAY = 379;
    private static final int CODE_INVOICE = 112;
    private static final int VALUE_TAX = 895;
    private static final int CODE_RECODES = 438;

    private TextView tv_name, tv_phone, tv_address;

    private TextView tv_time;
    private EditText et_car, et_send, et_remark;
    private TextView tv_pay_type;

    private TextView tv_invoice;
    private TextView tv_all_price;
    private TextView tv_amount_price;//活动优惠金额
    private TextView tv_goods_price;
    private TextView tv_install_price;
    private TextView tv_freight_price;
    private TextView tv_fwfee;
    private TextView tv_subtract, install_text;
    private RelativeLayout ll_install;
    private LinearLayout ll_bbb;
    private View line1;

    private TextView recordsName;

    private String allMoney;

    private final static int CODE_PACT = 592;
    private TextView tv_pact;
    AlertDialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_order);
        initData();
        initView();
    }

    private List<SpecialShopMolder> mList = new ArrayList<>();
    private boolean flag;
    private double total;
    private YusuanOrderBean yuSuanBean;
    private int statu = 0;
    private int orderType = 0;

    private void initData() {
        statu = getIntent().getIntExtra("statu", 0);
        orderType = getIntent().getIntExtra("orderType", 0);
        if (statu == 0) {
            dataList = (List<ProjectChild1>) getIntent().getSerializableExtra("dataList");
            bean = (ProjectBean) getIntent().getSerializableExtra("bean");
            yuSuanBean = (YusuanOrderBean) getIntent().getSerializableExtra("bean99");

        } else {
            yuSuanBean = (YusuanOrderBean) getIntent().getSerializableExtra("bean");
            List<YusuanOrderBean.InfoEntity.DataEntity> list = yuSuanBean.getInfo().getData();
            for (int i = 0; i < list.size(); i++) {
                ProjectChild1 p = new ProjectChild1();
                p.setSelect(false);
                p.setCart_id(list.get(i).getCart_id());
                p.setPackage_name(list.get(i).getPackage_name());
                p.setRoom_number(list.get(i).getRoom_number());
                p.setImg(list.get(i).getImg());
                p.setPackage_sku_info(list.get(i).getPackage_sku_info());
                p.setPackage_money(list.get(i).getPackage_money());
                p.setNums(list.get(i).getNums());
                p.setPackage_cate(list.get(i).getPackage_cate());
                dataList.add(p);
            }
            recordsId = Integer.parseInt(yuSuanBean.getInfo().getRecord_id());

        }
        allMoney = getIntent().getStringExtra("allMoney");


    }

    private void initView() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        if (statu == 0)
            title.setText("项目下单");
        else
            title.setText("预算项目下单");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        my_listView = (NoScrollListView) findViewById(R.id.my_listView);
        recordsName = (TextView) findViewById(R.id.recordsName);
        if (statu != 0) {
            recordsName.setText(yuSuanBean.getInfo().getProject_name() + "");
        }
        findViewById(R.id.rl_has_address).setOnClickListener(this);
        findViewById(R.id.rl_add_address).setOnClickListener(this);
        findViewById(R.id.iv_cost).setOnClickListener(this);
        findViewById(R.id.tv_send).setOnClickListener(this);
        findViewById(R.id.rl_time).setOnClickListener(this);
        findViewById(R.id.rl_pay_type).setOnClickListener(this);
        findViewById(R.id.rl_pact).setOnClickListener(this);
        findViewById(R.id.rl_records).setOnClickListener(this);
        ll_bbb = (LinearLayout) findViewById(R.id.ll_bbb);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_pay_type = (TextView) findViewById(R.id.tv_pay_type);
        tv_fwfee = (TextView) findViewById(R.id.tv_fwfee);
        if (yuSuanBean.getInfo().getIs_b().equals("1")) {
            ll_bbb.setVisibility(View.GONE);
        } else {
            ll_bbb.setVisibility(View.VISIBLE);
            tv_fwfee.setText("(总安装费：" + yuSuanBean.getInfo().getInstall_fee() + "元)");
        }
        tv_invoice = (TextView) findViewById(R.id.tv_invoice);
        tv_all_price = (TextView) findViewById(R.id.tv_all_price);
        tv_amount_price = (TextView) findViewById(R.id.tv_amount_price);
        tv_goods_price = (TextView) findViewById(R.id.tv_goods_price);
        tv_install_price = (TextView) findViewById(R.id.tv_install_price);
        tv_freight_price = (TextView) findViewById(R.id.tv_freight_price);

        et_car = (EditText) findViewById(R.id.et_car);
        et_send = (EditText) findViewById(R.id.et_send);
        et_remark = (EditText) findViewById(R.id.et_remark);

        rl_has_address = (RelativeLayout) findViewById(R.id.rl_has_address);//有地址
        rl_add_address = (RelativeLayout) findViewById(R.id.rl_add_address);//无收货地址

        rl_has_address.setVisibility(View.GONE);// TODO  暂时设为不可见

        sw_service = (SwitchView) findViewById(R.id.sw_service);//服务费
        sw_need = (SwitchView) findViewById(R.id.sw_need);//发票信息
        sw_special = (SwitchView) findViewById(R.id.sw_special);//申请特批
        ll_install = (RelativeLayout) findViewById(R.id.ll_install);
        line1 = findViewById(R.id.line1);
        install_text = (TextView) findViewById(R.id.install_text);
//        if (yuSuanBean.getInfo().getIs_b().equals("1")) {
//            ll_install.setVisibility(View.GONE);
//            line1.setVisibility(View.GONE);
//        } else {
//            install_text.setText("是否安装(总安装费：" + yuSuanBean.getInfo().getInstall_fee() + "元)");
//        }
        sw_install = (SwitchView) findViewById(R.id.sw_install);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_address = (TextView) findViewById(R.id.tv_address);

        rl_service = (RelativeLayout) findViewById(R.id.rl_service);
        rl_message = (RelativeLayout) findViewById(R.id.rl_message);
        rl_special = (RelativeLayout) findViewById(R.id.rl_special);
        rl_special_money = (RelativeLayout) findViewById(R.id.rl_special_money);
        sw_install.setOpened(false);
        sw_install.setOnStateChangedListener(this);
        sw_service.setOpened(false);
        sw_service.setOnStateChangedListener(this);
        sw_need.setOpened(false);
        sw_need.setOnStateChangedListener(this);

        sw_special.setOpened(false);
        sw_special.setOnStateChangedListener(this);
        rl_service.setVisibility(View.GONE);
        rl_message.setVisibility(View.GONE);
        rl_special.setVisibility(View.GONE);
        rl_special_money.setVisibility(View.GONE);

        if (flag) {
            sw_special.setOpened(true);
            //   rl_service.setVisibility(View.VISIBLE);
            rl_message.setVisibility(View.VISIBLE);
            rl_special.setVisibility(View.VISIBLE);
            rl_special_money.setVisibility(View.VISIBLE);
        }


        rl_special.setOnClickListener(this);
        rl_message.setOnClickListener(this);

        my_listView = (NoScrollListView) findViewById(R.id.my_listView);
        tv_pact = (TextView) findViewById(R.id.tv_pact);
        upload();
    }

    private static final String TAG = "ProjectOrderActivity";
    private String addrId = "";
    private String url;
    private String msg;
    private ProjectOrderBean bean_max = new ProjectOrderBean();

    private void upload() {
        final Map<String, Object> map = new HashMap<>();
        StringBuilder builder = new StringBuilder("-");
        if (MyApplication.getInstance().getUserBean() == null) {
            MyToast("请重新登录");
            return;
        }
        if (dataList == null) {
            MyToast("没有数据");
            return;
        }

        for (int i = 0; i < dataList.size(); i++) {
            builder.append(dataList.get(i).getCart_id());
            builder.append("-");
        }

        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("cartIds", builder);
        XUtil.Post(Url.ORDER_BUDGETBUYPAGE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess:ORDER_BUDGETBUYPAGE= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {

                        Gson gson = new Gson();
                        bean_max = gson.fromJson(jsonObject.optString("info"), ProjectOrderBean.class);
                        beanList = bean_max.getData();

                        JSONObject jsonObject1 = jsonObject.optJSONObject("contract");
                        url = jsonObject1.optString("url");
                        msg = jsonObject1.optString("msg");

                        mAdapter = new ProjectOrderAdapter(ProjectOrderActivity.this, beanList);
                        my_listView.setAdapter(mAdapter);

                        tv_goods_price.setText(bean_max.getTotal_price());
                        tv_install_price.setText(bean_max.getInstall_fee());
                        tv_all_price.setText(bean_max.getTotal_fee());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFinished() {
                super.onFinished();
                getBudgetActivityInfo(map);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void getBudgetActivityInfo(Map<String, Object> map) {
        XUtil.Post(Url.ORDER_BUDGETACTIVITYINFO, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess:ORDER_BUDGETACTIVITYINFO= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String youhuiStr= jsonObject.optString("info");
                    if ("1".equals(res)) {

                        AlertDialog.Builder builder = new AlertDialog.Builder(ProjectOrderActivity.this);
                        builder.setMessage(youhuiStr);
                        builder.setTitle("满减活动");
                        builder.setNegativeButton("好的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();

                            }
                        });

                        builder.create().show();

                        double amount = jsonObject.optDouble("amount");
                        if (amount > 0) {
                            tv_all_price.setText(String.valueOf(Double.parseDouble(bean_max.getTotal_fee()) - amount));
                            tv_amount_price.setVisibility(View.VISIBLE);
                            tv_amount_price.setText("已优惠：" + amount);
                            tv_goods_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                        } else {
                            tv_amount_price.setVisibility(View.GONE);
                            tv_goods_price.getPaint().setFlags(0);
                            tv_all_price.setText(bean_max.getTotal_fee());
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.rl_records:
                intent = new Intent(this, AddRecordsCodeActivity.class);
                startActivityForResult(intent, CODE_RECODES);
                break;
            //有地址，前去修改
            case R.id.rl_has_address:
                intent = new Intent(this, ChooseAddressActivity.class);
                startActivityForResult(intent, CODE_ADDRESS);
                break;

            //无地址，添加收货地址
            case R.id.rl_add_address:
                intent = new Intent(this, ChooseAddressActivity.class);
                startActivityForResult(intent, CODE_ADDRESS);
                break;

            //特批商品信息
            case R.id.rl_special:
                ArrayList<ProjectChild1> dataList1 = (ArrayList<ProjectChild1>) dataList;
                ArrayList<SpecialShopMolder> mList2 = (ArrayList<SpecialShopMolder>) mList;
                //  MyToast(""+mList2.size()+"-----2222----");
                startActivityForResult(new Intent(this, SpecialShopActivity.class).putExtra("dataList", dataList1)
                        .putExtra("bean", bean).putExtra("allMoney", allMoney).putExtra("discount", bean_max.getDiscount()).putExtra("mList222", mList2), 100);
                break;

            //付款方式
            case R.id.rl_pay_type:
                intent = new Intent(this, PayTypeActivity.class);
                intent.putExtra("name", dataList.get(0).getPackage_cate());
                intent.putExtra("from", "1");
                startActivityForResult(intent, CODE_PAY);
                break;

            //合同
            case R.id.rl_pact:
                if (recordsId == -1) {
                    MyToast("备案项目为空");
                    return;
                }

                if (payType.equals("")) {
                    MyToast("请选择支付方式");
                    return;
                }

                String cartId = "-";   //套餐id
                for (int i = 0; i < dataList.size(); i++) {
                    cartId = cartId + dataList.get(i).getCart_id() + "-";
                }

                Log.e(" === 进入选择合同界面cartId==", cartId);
//                startActivity(PactTypeActivity.createIntent(this, "" + recordsId,  payType,  cartId));

                intent = new Intent(this, PactTypeActivity.class);
                intent.putExtra("recordsId", "" + recordsId);
                intent.putExtra("payType", payType);
                intent.putExtra("cartIds", cartId);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, CODE_PACT);

                break;

           /* //服务费
            case R.id.iv_cost:
                break;*/

            //发票信息
            case R.id.rl_message:
                intent = new Intent(this, SelectFapiaoActivity.class);
                startActivityForResult(intent, CODE_INVOICE);

                break;

            //时间
            case R.id.rl_time:
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();//取时间
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(calendar.DATE, 8);//把日期往后增加一天.整数往后推,负数往前移动
                date = calendar.getTime();   //这个时间就是日期往后推一天的结果
//                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(date);
                OrderTime dataPicker = new OrderTime(ProjectOrderActivity.this);
                dataPicker.selectDateDialog(tv_time, str, "start");

                String todayTime = tv_time.getText().toString();
                break;

            //提交
            case R.id.tv_send:

                time = tv_time.getText().toString();
                //   payType = tv_pay_type.getText().toString();
                String invoice = tv_invoice.getText().toString();
                final String pact = tv_pact.getText().toString();
                if ("1".equals(need)) {
                    if (!"".equals(invoice) && !"".equals(time) && !"".equals(payType) && !"".equals(pact)) {
                        invoicType = "1";


                        AlertDialog.Builder builder = new AlertDialog.Builder(ProjectOrderActivity.this);
                        View view = View
                                .inflate(ProjectOrderActivity.this, R.layout.dialog_simple_alert, null);
                        builder.setView(view);
                        builder.setCancelable(true);
                        TextView tv_tip= (TextView) view
                                .findViewById(R.id.tv_tip);//设置标题

                        TextView btn_cancel=(TextView)view
                                .findViewById(R.id.cancel);//取消按钮
                        TextView btn_comfirm=(TextView)view
                                .findViewById(R.id.confirm);//确定按钮

                        TextView tv_content=(TextView)view
                                .findViewById(R.id.content);//确定按钮
                        tv_tip.setText("提示");

                        tv_content.setText("确定提交订单");
                        btn_comfirm.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                upSubmit(invoicType);
                            }
                        });
                        btn_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        //取消或确定按钮监听事件处理
                        dialog = builder.create();
                        dialog.show();







                    } else if ("".equals(invoice)) {
                        MyToast("请选择发票");
                    } else if ("".equals(time)) {
                        MyToast("配送日期不能为空");
                    } else if ("".equals(payType)) {
                        MyToast("付款方式不能为空");
                    } else if ("".equals(pact)) {
                        MyToast("合同不能为空");
                    } else if (-1 == recordsId) {
                        MyToast("请选择备案项目");
                    }
                } else {
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
                    builder1.setMessage("您未选择发票，如果确定不需要发票，后续将不会进行补发，如有问题请联系客服")
                            .setTitle("提示")
                            .setCancelable(false)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    if (!"".equals(time) && !"".equals(payType) && !"".equals(pact)) {
                                        invoicType = "3";
                                        AlertDialog.Builder builder = new AlertDialog.Builder(ProjectOrderActivity.this);
                                        builder.setMessage("确认提交订单？")
                                                .setCancelable(false)
                                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        upSubmit(invoicType);
                                                    }
                                                })
                                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        dialog.cancel();
                                                    }
                                                });
                                        AlertDialog alert = builder.show();

                                    } else if ("".equals(time)) {
                                        MyToast("配送日期不能为空");
                                    } else if ("".equals(payType)) {
                                        MyToast("付款方式不能为空");
                                    } else if ("".equals(pact)) {
                                        MyToast("合同不能为空");
                                    } else if (-1 == recordsId) {
                                        MyToast("请选择备案项目");
                                    }

                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();

                                }
                            });
                    AlertDialog alert = builder1.show();

                }
                break;

            default:
                break;
        }
    }

    private String car = "";
    private String send = "";
    private String remark = "";
    private String time = "";
    private String payType = "";
    private String install = "";
    private String need = "0";
    private String invoicType;

    private void upSubmit(String invoicType) {
        car = et_car.getText().toString();
        send = et_send.getText().toString();
        remark = et_remark.getText().toString();
        Map<String, Object> map = new HashMap<>();
        StringBuilder builder = new StringBuilder("-");
        for (int i = 0; i < beanList.size(); i++) {
            builder.append(beanList.get(i).getCart_id());
            builder.append("-");
        }
        map.put("addressId", addrId);
        map.put("cartIds", builder);
        map.put("contract", tv_pact.getText());
        map.put("deliver_time", time);
        map.put("if_receipt", need);
        map.put("pay_way", "" + payType);
        map.put("if_install", if_install);
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        if (mList.size() > 0) {
            map.put("if_tepi", 1);
            StringBuffer tepi_goods = new StringBuffer("[");
            for (int i = 0; i < mList.size(); i++) {
                tepi_goods.append("   {\n" +
                        "             \"apply_price\":" + mList.get(i).getTePiPrice() + ",\n" +
                        "            \"budget_package_id\":" + mList.get(i).getId() + ",\n" +
                        "             \"package_id\":" + mList.get(i).getPackage_id() + ",\n" +
                        "             \"package_price\":" + Double.parseDouble(beanList.get(i).getPackage_money()) + "\n" +
                        "             }");
                if (i != mList.size() - 1) {
                    tepi_goods.append(",");
                }
            }
            tepi_goods.append("]");
            map.put("tepi_goods", tepi_goods.toString());
            Log.e("----tepi_goods", tepi_goods.toString());

        } else {
            map.put("if_tepi", 0);
        }
        map.put("record_id", recordsId);

        map.put("if_install", if_install);
        map.put("deliver_requir", send);
        map.put("vehicle_requir", car);
        map.put("message", remark);
        map.put("receiptAddrId", receiptAddrId);
        map.put("invoiceType", invoicType);
        map.put("invoiceTitle", invoiceTitle);
        map.put("header_type", invoiceType);
        map.put("company", company);
        map.put("taxpayerId", taxpayerId);
        map.put("address", address);
        map.put("phone", phone);
        map.put("bank", bank);
        map.put("bankAccount", bankAccount);
        map.put("receiptType", receiptType);

        map.put("if_receipt", need);
        if ("1".equals(need)) {
            map.put("invoiceId", invoiceId);
        }

        if (tv_pact.getText().equals("标准合同")) {
            map.put("hetong_type", 1);
            map.put("hetong_name", Prefer.getInstance().getHTJiaFang());
            map.put("hetong_address", Prefer.getInstance().getHTAddress());
            map.put("hetong_tel", Prefer.getInstance().getHTPhone());

            if (!TextUtils.isEmpty(Prefer.getInstance().getHTChuanZhen())) {
                map.put("hetong_fax", Prefer.getInstance().getHTChuanZhen());
            }

            map.put("hetong_addr", Prefer.getInstance().getHTJioaHuo());
            System.out.println("Prefer.getInstance().getHTJioaHuo()=="+Prefer.getInstance().getHTJioaHuo());
            map.put("hetong_realname", Prefer.getInstance().getHTShouHuoren());
            map.put("hetong_number", Prefer.getInstance().getHTShenFenzheng());

        } else if (tv_pact.getText().equals("自定义合同")) {
            map.put("hetong_type", 0);
        }

        String urlStr = "";
        if (statu == 0) {

            map.put("equipment", "android");
            map.put("version", "" + SystemUtils.getVersionName(ProjectOrderActivity.this));
            urlStr = Url.ORDER_BUDGETMAKEORDER;

        } else {

            map.put("yusuan_id", yuSuanBean.getInfo().getYusuan_id());
            urlStr = Url.BATH_BUDGETMAKEORDER;
        }

        if (orderType == 1) {
            urlStr = Url.BATH_BUDGETMAKEORDER;
        }

        Map<String, Object> map2 = new HashMap<>();
        Set set = map.entrySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry mapentry = (Map.Entry) iterator.next();
            Log.e("=====" + mapentry.getKey() + "", mapentry.getValue() + "");
            map2.put("" + mapentry.getKey(), mapentry.getValue());
        }

        XUtil.Post(urlStr, map2, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Log.i(TAG, "onSuccess:deliver_requir= " + result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String res = jsonObject.optString("result");
                            String info = jsonObject.optString("info");
                            Log.i(TAG, "onSuccess:deliver_requir= " + info);
                            if ("1".equals(res)) {
                                if (tv_pact == null || tv_pact.getText().toString().trim().equals("自定义合同")) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(ProjectOrderActivity.this);
                                    final View view = View.inflate(ProjectOrderActivity.this, R.layout.dialog_project_order, null);
                                    builder.setView(view);
                                    builder.setCancelable(false);
                                    final AlertDialog show = builder.show();
                                    Window dialogWindow = show.getWindow();
                                    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                                    dialogWindow.setGravity(Gravity.CENTER);
                                    dialogWindow.setAttributes(lp);
                                    TextView queding1 = (TextView) view.findViewById(R.id.queding1);
                                    TextView textView = (TextView) view.findViewById(R.id.text);
                                    textView.setText("\"尊敬的" + MyApplication.getInstance().getUserBean().getUserName() + "，您的" + recordsName.getText() + "项目已经成功提交，请到（www.uhousing.cn)登录并上传合同，未上传合同订单将处于未处理状态。\"");
                                    queding1.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            show.dismiss();
                                            setResult(1, null);
                                            finish();
                                        }
                                    });
                                }  else if (tv_pact == null || tv_pact.getText().toString().trim().equals("标准合同")) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(ProjectOrderActivity.this);
                                    final View view = View.inflate(ProjectOrderActivity.this, R.layout.dialog_project_order, null);
                                    builder.setView(view);
                                    builder.setCancelable(false);
                                    final AlertDialog show = builder.show();
                                    Window dialogWindow = show.getWindow();
                                    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                                    dialogWindow.setGravity(Gravity.CENTER);
                                    dialogWindow.setAttributes(lp);
                                    TextView queding1 = (TextView) view.findViewById(R.id.queding1);
                                    TextView textView = (TextView) view.findViewById(R.id.text);
                                    textView.setText("\"尊敬的" + MyApplication.getInstance().getUserBean().getUserName() + "，您的" + recordsName.getText() + "项目已提交成功，请通过（www.uhousing.cn)登录并上传相关附件。");

                                    queding1.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            show.dismiss();
                                            setResult(1, null);
                                            finish();
                                        }
                                    });
                                }

                                else {
                                    MyToast("下单成功！等待审核" );

                                    setResult(1, null);
                                    finish();
                                }
                            } else {
                                MyToast(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                    }
                }
        );
    }


    private String receiptAddrId = "";
    private String invoiceType = "";
    private String invoiceTitle = "";
    private String company = "";
    private String receiptType = "";
    private String type = "";

    private String taxpayerId = "";
    private String bank = "";
    private String bankAccount = "";
    private String address = "";
    private String phone = "";
    private String getInvoiceResult = "";
    private int recordsId = -1;

    private String invoiceId = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CODE_RECODES:
                if (resultCode == RESULT_OK) {
                    recordsId = Integer.parseInt(data.getStringExtra("recordsId"));
                    Log.e("==备案id===", "" + recordsId);
                    String name = data.getStringExtra("recordsName");
                    recordsName.setText(name + "");
                }
                break;
            case 100:
                if (resultCode == 1) {
                    flag = data.getBooleanExtra("tePiFlag", false);
                    if (flag) {
                        tv_subtract = (TextView) findViewById(R.id.tv_subtract);
                        mList = (List<SpecialShopMolder>) data.getSerializableExtra("specialShop");
                        total = 0;
                        DecimalFormat df = new DecimalFormat("######0.00");
                        for (int i = 0; i < mList.size(); i++) {
                            total += Double.parseDouble(df.format(Double.parseDouble(mList.get(i).getOther_tepi().trim())));
                        }
                        tv_subtract.setText("¥ " + total);

                    }
                }
                //地址回调
            case CODE_ADDRESS:
                if (resultCode == RESULT_OK) {
                    if (null != data) {
                        AddressBean addressBean = (AddressBean) data.getSerializableExtra("addressBean");
                        rl_has_address.setVisibility(View.VISIBLE);
                        rl_add_address.setVisibility(View.GONE);
                        String province = addressBean.getProvince();
                        String city = addressBean.getCity();
                        String district = addressBean.getDistrict();
                        String place = addressBean.getPlace();
                        String addr = province + city + district + place;
                        tv_name.setText(addressBean.getConsignee());
                        tv_phone.setText(addressBean.getTelephone());
                        tv_address.setText(addr);
                        addrId = addressBean.getAddress_id();
                    }
                }
                break;

            //付款方式回调
            case CODE_PAY:
                if (resultCode == RESULT_OK) {
                    if (null != data) {
                        String name = data.getStringExtra("pay");
                        payType = data.getStringExtra("payId");

                        Log.e("==付款id===", "" + payType);
                        tv_pay_type.setText(name);
                    }
                }
                break;

            //发票回调
            case CODE_INVOICE:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra("name");
                    invoiceId = data.getStringExtra("id");
                    tv_invoice.setText(name + "");
                }
                break;

            //合同回调
            case CODE_PACT:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String pact = data.getStringExtra("pact");
                        if ("0".equals(pact)) {
                            tv_pact.setText("自定义合同");
                        }
                        if ("1".equals(pact)) {
                            tv_pact.setText("标准合同");
                        }
                    }
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void toggleToOn(View view) {
        switch (view.getId()) {
            case R.id.sw_install:
                sw_install.setOpened(true);
                if_install = 1;
                try {
                    tv_all_price.setText("" + (Double.parseDouble(bean_max.getTotal_fee()) + Double.parseDouble(yuSuanBean.getInfo().getInstall_fee())));
                } catch (Exception e) {
                    e.printStackTrace();
                    tv_all_price.setText("0");
                }
                break;
            //申请特批
            case R.id.sw_special:
                sw_special.setOpened(true);
                showOrHidePickLayout3(true);
                break;

            //服务费
            case R.id.sw_service:
                sw_service.setOpened(true);
                showOrHidePickLayout1(true);
                install = "1";
                if_install = 1;
                tv_all_price.setText("" + (Double.parseDouble(bean_max.getTotal_fee()) + Double.parseDouble(yuSuanBean.getInfo().getInstall_fee())));

                break;

            //发票信息
            case R.id.sw_need:
                sw_need.setOpened(true);
                showOrHidePickLayout2(true);
                need = "1";
                break;

            default:
                break;
        }
    }

    private int if_install = 0;

    @Override
    public void toggleToOff(View view) {
        switch (view.getId()) {
            case R.id.sw_install:
                try {
                    tv_all_price.setText("" + bean_max.getTotal_fee());
                } catch (Exception e) {
                    tv_all_price.setText("0");
                    e.printStackTrace();
                }
                sw_install.setOpened(false);
                if_install = 0;
                break;
            case R.id.sw_special:
                sw_special.setOpened(false);
                showOrHidePickLayout3(false);
                break;

            case R.id.sw_service:
                sw_service.setOpened(false);
                showOrHidePickLayout1(false);
                if_install = 1;
                install = "0";
                tv_all_price.setText("" + (Double.parseDouble(bean_max.getTotal_fee())));
                break;

            case R.id.sw_need:
                sw_need.setOpened(false);
                showOrHidePickLayout2(false);
                need = "0";
                break;

            default:
                break;
        }
    }

    private void showOrHidePickLayout1(boolean isNeedToPick) {

        if (isNeedToPick) {
            rl_service.setVisibility(View.VISIBLE);
        } else {
            rl_service.setVisibility(View.GONE);
        }
    }

    private void showOrHidePickLayout2(boolean isNeedToPick) {

        if (isNeedToPick) {
            rl_message.setVisibility(View.VISIBLE);
        } else {
            rl_message.setVisibility(View.GONE);
        }
    }

    private void showOrHidePickLayout3(boolean isNeedToPick) {

        if (isNeedToPick) {
            rl_special.setVisibility(View.VISIBLE);
            rl_special_money.setVisibility(View.VISIBLE);
        } else {
            rl_special.setVisibility(View.GONE);
            rl_special_money.setVisibility(View.GONE);
        }
    }

    private double getdoublePrice(double price) {
        BigDecimal d = new BigDecimal(price);
        return d.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }


}
